package com.tianji.learning.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@RequiredArgsConstructor
public class LessonListener {

    private final ILearningLessonService lessonService;

    /**
     * 监听订单支付或课程报名的消息
     *
     * @param order
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.Queue.ORDER_PAY_QUEUE, durable = "true"),
            exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenLessonPay(OrderBasicDTO order) {
        if (ObjectUtil.isEmpty(order) || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())) {
            log.error("订单数据为空,{}", order);
            return;
        }
        log.info("监听到{}用户的订单{}，需要添加课程{}到课表中", order.getUserId(), order.getOrderId(), order.getCourseIds());
        lessonService.addUserLessons(order.getUserId(), order.getCourseIds());
    }

    /**
     * 监听订单取消的消息
     *
     * @param order
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.Queue.ORDER_CANCEL_QUEUE, durable = "true"),
            exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenerLessonRefund(OrderBasicDTO order) {
        if (ObjectUtil.isEmpty(order) || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())) {
            log.error("订单数据为空,{}", order);
            return;
        }
        log.info("监听到{}用户要取消订单{}，需要取消用户报名的课程{}", order.getUserId(), order.getOrderId(), order.getCourseIds());
        lessonService.removeUserLessons(order.getUserId(), order.getCourseIds());
    }
}
